﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Drawing;

namespace AyuBookmark.WinForm.Dialogs
{
    /// <summary>
    /// 数据备份与恢复对话框
    /// </summary>
    public partial class BackupRestoreDialog : Form
    {
        private TabControl tabControl;
        private TabPage tabBackup;
        private TabPage tabRestore;
        private Button btnBackupBrowse;
        private Button btnRestoreBrowse;
        private Button btnBackupNow;
        private Button btnRestoreNow;
        private Button btnCancel;
        private TextBox txtBackupPath;
        private TextBox txtRestorePath;
        private ProgressBar progressBar;
        private Label lblStatus;

        public BackupRestoreDialog()
        {
            InitializeComponent();
            SetupDefaultPaths();
        }

        private void InitializeComponent()
        {
            // 窗体基础设置
            this.SuspendLayout();
            this.Text = "数据备份与恢复";
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ClientSize = new Size(500, 350);
            this.Padding = new Padding(10);

            // 选项卡控件
            this.tabControl = new TabControl();
            this.tabControl.Dock = DockStyle.Fill;

            // 备份选项卡
            this.tabBackup = new TabPage("备份数据");
            this.tabBackup.Padding = new Padding(10);

            // 恢复选项卡
            this.tabRestore = new TabPage("恢复数据");
            this.tabRestore.Padding = new Padding(10);

            // 备份路径选择控件
            var backupPanel = new Panel();
            backupPanel.Dock = DockStyle.Top;
            backupPanel.Height = 40;

            this.txtBackupPath = new TextBox();
            this.txtBackupPath.Dock = DockStyle.Fill;
            this.txtBackupPath.Margin = new Padding(0, 0, 5, 0);

            this.btnBackupBrowse = new Button();
            this.btnBackupBrowse.Text = "浏览...";
            this.btnBackupBrowse.Dock = DockStyle.Right;
            this.btnBackupBrowse.Width = 80;
            this.btnBackupBrowse.Click += (s, e) => BrowseBackupPath();

            backupPanel.Controls.Add(this.txtBackupPath);
            backupPanel.Controls.Add(this.btnBackupBrowse);

            // 备份按钮
            this.btnBackupNow = new Button();
            this.btnBackupNow.Text = "开始备份";
            this.btnBackupNow.Dock = DockStyle.Bottom;
            this.btnBackupNow.Height = 40;
            this.btnBackupNow.Click += (s, e) => StartBackup();

            // 恢复路径选择控件
            var restorePanel = new Panel();
            restorePanel.Dock = DockStyle.Top;
            restorePanel.Height = 40;

            this.txtRestorePath = new TextBox();
            this.txtRestorePath.Dock = DockStyle.Fill;
            this.txtRestorePath.Margin = new Padding(0, 0, 5, 0);

            this.btnRestoreBrowse = new Button();
            this.btnRestoreBrowse.Text = "浏览...";
            this.btnRestoreBrowse.Dock = DockStyle.Right;
            this.btnRestoreBrowse.Width = 80;
            this.btnRestoreBrowse.Click += (s, e) => BrowseRestorePath();

            restorePanel.Controls.Add(this.txtRestorePath);
            restorePanel.Controls.Add(this.btnRestoreBrowse);

            // 恢复按钮
            this.btnRestoreNow = new Button();
            this.btnRestoreNow.Text = "开始恢复";
            this.btnRestoreNow.Dock = DockStyle.Bottom;
            this.btnRestoreNow.Height = 40;
            this.btnRestoreNow.Click += (s, e) => StartRestore();

            // 进度条
            this.progressBar = new ProgressBar();
            this.progressBar.Dock = DockStyle.Bottom;
            this.progressBar.Height = 20;
            this.progressBar.Style = ProgressBarStyle.Continuous;

            // 状态标签
            this.lblStatus = new Label();
            this.lblStatus.Dock = DockStyle.Bottom;
            this.lblStatus.Height = 30;
            this.lblStatus.TextAlign = ContentAlignment.MiddleLeft;

            // 取消按钮
            this.btnCancel = new Button();
            this.btnCancel.Text = "取消";
            this.btnCancel.Dock = DockStyle.Bottom;
            this.btnCancel.Height = 40;
            this.btnCancel.DialogResult = DialogResult.Cancel;

            // 添加控件到备份选项卡
            this.tabBackup.Controls.Add(this.btnBackupNow);
            this.tabBackup.Controls.Add(backupPanel);
            this.tabBackup.Controls.Add(this.progressBar);
            this.tabBackup.Controls.Add(this.lblStatus);

            // 添加控件到恢复选项卡
            this.tabRestore.Controls.Add(this.btnRestoreNow);
            this.tabRestore.Controls.Add(restorePanel);
            this.tabRestore.Controls.Add(this.progressBar);
            this.tabRestore.Controls.Add(this.lblStatus);

            // 添加选项卡
            this.tabControl.Controls.Add(this.tabBackup);
            this.tabControl.Controls.Add(this.tabRestore);

            // 添加主控件
            this.Controls.Add(this.tabControl);
            this.Controls.Add(this.btnCancel);

            this.ResumeLayout(false);
        }

        private void SetupDefaultPaths()
        {
            // 设置默认备份路径
            string backupDir = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                "AyuBookmark Backups");

            if (!Directory.Exists(backupDir))
            {
                Directory.CreateDirectory(backupDir);
            }

            this.txtBackupPath.Text = Path.Combine(backupDir,
                $"backup_{DateTime.Now:yyyyMMdd}.abk");

            // 自动查找最新的备份文件
            var backupFiles = Directory.GetFiles(backupDir, "*.abk");
            if (backupFiles.Length > 0)
            {
                this.txtRestorePath.Text = backupFiles[0]; // 使用第一个找到的备份文件
            }
        }

        private void BrowseBackupPath()
        {
            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "AyuBookmark备份文件 (*.abk)|*.abk|所有文件 (*.*)|*.*";
                saveDialog.DefaultExt = "abk";
                saveDialog.InitialDirectory = Path.GetDirectoryName(this.txtBackupPath.Text);
                saveDialog.FileName = Path.GetFileName(this.txtBackupPath.Text);

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    this.txtBackupPath.Text = saveDialog.FileName;
                }
            }
        }

        private void BrowseRestorePath()
        {
            using (var openDialog = new OpenFileDialog())
            {
                openDialog.Filter = "AyuBookmark备份文件 (*.abk)|*.abk|所有文件 (*.*)|*.*";
                openDialog.DefaultExt = "abk";
                openDialog.InitialDirectory = Path.GetDirectoryName(this.txtRestorePath.Text);

                if (openDialog.ShowDialog() == DialogResult.OK)
                {
                    this.txtRestorePath.Text = openDialog.FileName;
                }
            }
        }

        private void StartBackup()
        {
            if (string.IsNullOrWhiteSpace(this.txtBackupPath.Text))
            {
                MessageBox.Show("请选择备份文件路径", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                this.lblStatus.Text = "正在备份数据...";
                this.progressBar.Value = 0;
                this.btnBackupNow.Enabled = false;

                // 模拟备份过程
                for (int i = 0; i <= 100; i++)
                {
                    this.progressBar.Value = i;
                    System.Threading.Thread.Sleep(50); // 模拟耗时操作
                }

                // TODO: 实际备份逻辑
                // File.WriteAllText(this.txtBackupPath.Text, SerializeData());

                this.lblStatus.Text = "备份完成！";
                MessageBox.Show("数据备份成功", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                this.lblStatus.Text = "备份失败";
                MessageBox.Show($"备份过程中出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.btnBackupNow.Enabled = true;
            }
        }

        private void StartRestore()
        {
            if (string.IsNullOrWhiteSpace(this.txtRestorePath.Text))
            {
                MessageBox.Show("请选择要恢复的备份文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!File.Exists(this.txtRestorePath.Text))
            {
                MessageBox.Show("指定的备份文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var result = MessageBox.Show("恢复操作将覆盖当前数据，是否继续？", "警告",
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result != DialogResult.Yes) return;

            try
            {
                this.lblStatus.Text = "正在恢复数据...";
                this.progressBar.Value = 0;
                this.btnRestoreNow.Enabled = false;

                // 模拟恢复过程
                for (int i = 0; i <= 100; i++)
                {
                    this.progressBar.Value = i;
                    System.Threading.Thread.Sleep(50); // 模拟耗时操作
                }

                // TODO: 实际恢复逻辑
                // var data = File.ReadAllText(this.txtRestorePath.Text);
                // DeserializeData(data);

                this.lblStatus.Text = "恢复完成！";
                MessageBox.Show("数据恢复成功", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                this.lblStatus.Text = "恢复失败";
                MessageBox.Show($"恢复过程中出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.btnRestoreNow.Enabled = true;
            }
        }

        public static void ShowBackupRestoreDialog(IWin32Window owner)
        {
            using (var dialog = new BackupRestoreDialog())
            {
                dialog.ShowDialog(owner);
            }
        }
    }
}